<?php

namespace App\Service\Workflow;

use App\Models\Workflow\WorkflowOrderLogModel;
use App\Models\Workflow\WorkflowOrderModel;
use App\Models\Workflow\WorkflowOrderNodeModel;
use App\Service\BaseService;
use Illuminate\Support\Facades\Log;

class WorkflowHandlerUserService extends BaseService
{
    /**
     * 更换节点处理人
     * @param int $shopId
     * @param int $handlerType
     * @param int $handlerUid
     * @return void
     */
    public static function changeNodeHandlerUid(array $shopIds, int $handlerType, int $handlerUid, string $handlerName)
    {
        Log::warning("changeNodeHandlerUid start shopIds:" . json_encode($shopIds) . " handlerType:{$handlerType} handlerUid:{$handlerUid} handlerName:{$handlerName}");

        if (!$shopIds) {
            return;
        }

        if ($handlerType < 0) {
            return;
        }

        WorkflowOrderModel
            ::query()
            ->with([
                'nodesRel' => function ($query) use ($handlerType, $handlerUid, $handlerName) {
                    $query->where('status', '!=', WorkflowOrderNodeModel::STATUS_FINISH)
                          ->where('handlerType', $handlerType)
                          ->where('handlerUid', '!=', $handlerUid);
                }
            ])
            ->whereIn('shopId', $shopIds)
            ->where('status', WorkflowOrderModel::STATUS_ING)
            ->get()
            ->each(function (WorkflowOrderModel $workflowOrderModel) use ($handlerUid, $handlerName) {

                $workflowOrderModel->nodesRel
                    ->each(function (WorkflowOrderNodeModel $workflowOrderNodeModel) use ($handlerUid, $handlerName) {
                        $workflowOrderNodeModel->handlerUid = $handlerUid;
                        $workflowOrderNodeModel->save();

                        WorkflowOrderLogModel::query()
                                             ->where('workflowOrderNodeId', $workflowOrderNodeModel->id)
                                             ->update([
                                                 'handlerUid'  => $handlerUid,
                                                 'handlerName' => $handlerName
                                             ]);
                    });
            });
    }
}
